package rjeutsky.database.jpa.models;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.Session;

import rjeutsky.models.UserRole;

@Entity
@Table(name="UserRole")
public class JPAUserRole {
	
	private long id;
	private String name;
	private List<JPAUser> users;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@ManyToMany
	@JoinTable(name="UserUserRole", 
			joinColumns= {@JoinColumn(name="userRoleId")},
			inverseJoinColumns={@JoinColumn(name="userId")})	
	public List<JPAUser> getUsers() {
		return users;
	}
	public void setUsers(List<JPAUser> users) {
		this.users = users;
	}
	@Transient
	public UserRole getUserRole() {
		UserRole userRole = new UserRole();
		userRole.setId(id);
		userRole.setName(name);
		return userRole;
	}
	
	@Transient
	public static JPAUserRole getJPAUserRole(Session session, UserRole userRole) {
		if (userRole == null) {
			return null;
		}
		
		return (JPAUserRole) session.get(JPAUserRole.class, userRole.getId());
	}
	
	@Transient
	public static List<UserRole> getUserRoles(List<JPAUserRole> jpaUserRoles) {
		List<UserRole> userRoles = new LinkedList<UserRole>();
		if (jpaUserRoles != null) {
			for (JPAUserRole userRole : jpaUserRoles) {
				userRoles.add(userRole.getUserRole());
			}
		}
		
		return userRoles;
	}
}
